/**
 * 项目名：五位一体化工安全信息平台
 * 日期：    2019-11-25 11:05:10
 * Copyright (c) 2015- joysuch-版权所有
 */

package com.joysuch.wwyt.core.controller;

import java.util.ArrayList;
import java.util.List;

import javax.validation.Valid;

import cn.zlg.common.springmvc.validate.constraints.NotNull;
import com.joysuch.wwyt.bp.enums.DataStateTypes;
import com.joysuch.wwyt.core.bean.BaseTypeGroupBean;
import com.joysuch.wwyt.core.bean.TypeGroupItemBean;
import com.joysuch.wwyt.core.common.ajax.ResultBean;
import com.joysuch.wwyt.core.common.util.PinYinUtils;
import com.joysuch.wwyt.core.entity.BaseTypeGroup;
import com.joysuch.wwyt.core.entity.BaseTypeGroupItem;
import com.joysuch.wwyt.core.repository.BaseTypeGroupDao;
import com.joysuch.wwyt.core.repository.BaseTypeGroupItemDao;
import com.joysuch.wwyt.core.service.BaseTypeGroupService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/base/type-group")
@Api(tags = "系统管理-数据字典类型")
public class BaseTypeGroupController {

    private static final Logger logger = LoggerFactory.getLogger(BaseTypeGroupController.class);

    @Autowired
    private BaseTypeGroupService baseTypeGroupService;
    @Autowired
    private BaseTypeGroupDao baseTypeGroupDao;
    private BaseTypeGroupItemDao baseTypeGroupItemDao;

    @PostMapping("addType")
    @ApiOperation(value = "增加字典类型")
    @RequiresPermissions("base:type-group:addType")
    public ResultBean addType(@RequestBody BaseTypeGroupBean bean) {
        BaseTypeGroup group = baseTypeGroupService.addType(bean);
        return ResultBean.success(group);
    }

    @PostMapping("updateType")
    @ApiOperation(value = "修改字典类型")
    @RequiresPermissions("base:type-group:updateType")
    public ResultBean updateType(@RequestBody BaseTypeGroupBean bean) {
        BaseTypeGroup group = baseTypeGroupService.updateType(bean);
        return ResultBean.success(group);
    }

    @GetMapping("deleteType")
    @ApiOperation(value = "删除字典类型")
    @RequiresPermissions("base:type-group:deleteType")
    public ResultBean deleteType(Long id) {
        baseTypeGroupService.deleteType(id);
        return ResultBean.success("");
    }

    @GetMapping("pageType")
    @ApiOperation(value = "分页字典类型")
    public ResultBean pageType(Pageable page) {
        return baseTypeGroupService.pageType(page);
    }

    @GetMapping("getTypeList")
    @ApiOperation(value = "获取字典列表")
    public ResultBean getTypeList( ) {
        List<BaseTypeGroupBean> list = baseTypeGroupService.getTypeList();
        return ResultBean.success(list);
    }


    @RequestMapping("addType")
    public Object add(@Valid @NotNull(field = "字典项") String type, @Valid @NotNull(field = "字典项列表") String items) {
        try {
            BaseTypeGroup group = baseTypeGroupDao.findByName(type);
            String[] arr = items.split("(，)|(、)|(,)");
            if (group == null) {
                String abbrev = PinYinUtils.getHanziInitials(type);
                int index = 1;
                while (baseTypeGroupDao.findByCode(abbrev) != null) {
                    abbrev += index;
                    index++;
                }
                group = new BaseTypeGroup();
                group.setCode(abbrev);
                group.setName(type);
                group.setState(DataStateTypes.EFFECTIVE.getState());
                for (String s : arr) {
                    String trim = s.trim();
                    if (trim.length() > 0) {
                        BaseTypeGroupItem bs = new BaseTypeGroupItem();
                        bs.setCode(abbrev + "_" + PinYinUtils.getHanziInitials(trim));
                        bs.setName(trim);
                        bs.setState(DataStateTypes.EFFECTIVE.getState());
                        group.getBaseTypeGroupItems().add(bs);
                    }
                }
                baseTypeGroupDao.save(group);
            } else {
                group.getBaseTypeGroupItems().clear();
                for (String s : arr) {
                    String trim = s.trim();
                    if (trim.length() > 0) {
                        BaseTypeGroupItem bs = new BaseTypeGroupItem();
                        bs.setCode(group.getCode() + "_" + PinYinUtils.getHanziInitials(trim));
                        bs.setName(trim);
                        bs.setState(1);
                        group.getBaseTypeGroupItems().add(bs);
                    }
                }
                baseTypeGroupDao.save(group);
            }
            return ResultBean.success("");
        } catch (Exception e) {
            logger.error("创建失败", e);
            return ResultBean.fail(101, "创建失败");
        }
    }

    @RequestMapping("update")
    public Object update(@Valid BaseTypeGroup entity) {
        try {
            if (entity.getId() == null) {
                return ResultBean.fail(102, "未指定主键");
            }
            baseTypeGroupService.update(entity);
            return ResultBean.success("");
        } catch (Exception e) {
            logger.error("更新失败：#" + entity.getId(), e);
            return ResultBean.fail(101, "更新失败");
        }
    }

    @RequestMapping("list")
    public Object list(Pageable page) {
        try {
            List<BaseTypeGroup> findAll = baseTypeGroupDao.findAll();
            List<TypeGroupItemBean> list = new ArrayList<TypeGroupItemBean>();
            for (BaseTypeGroup b : findAll) {
                TypeGroupItemBean bean = new TypeGroupItemBean();
                bean.setCode(b.getCode());
                bean.setId(b.getId());
                bean.setName(b.getName());
                list.add(bean);
            }
            return ResultBean.success(list);
        } catch (Exception e) {
            logger.error("分页查询失败", e);
            return ResultBean.fail(101, "分页查询失败");
        }
    }

    @RequestMapping("page")
    public Object page(Pageable page) {
        try {
            Page<BaseTypeGroup> data = baseTypeGroupService.findByPage(page);
            return ResultBean.pageData(data.getContent(), data.getTotalElements());
        } catch (Exception e) {
            logger.error("分页查询失败", e);
            return ResultBean.fail(101, "分页查询失败");
        }
    }

    @RequestMapping("delete")
    public Object delete(Long id) {
        try {
            baseTypeGroupService.delete(id);
            return ResultBean.success("");
        } catch (Exception e) {
            logger.error("删除失败", e);
            return ResultBean.fail(101, "删除失败");
        }
    }
}
